package com.wyw.hemerocallis.service;

import com.wyw.hemerocallis.entity.HemerocallisPath;
import com.wyw.hemerocallis.permission.vo.CreatePathRequest;
import com.wyw.hemerocallis.repository.HemerocallisPathRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 路径相关功能的实现
 *
 * @author Mr Wu    yewen.wu.china@gmail.com
 * <p>
 * Update History:
 * Author        Time            Content
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PathService {

    private final HemerocallisPathRepository pathRepository;

    /**
     * 添加新的path到数据表中
     *
     * @param request  {@link CreatePathRequest}
     * @return Path 数据记录的主键
     */
    public List<Integer> createPath(CreatePathRequest request) {
        List<CreatePathRequest.PathInfo> pathInfos = request.getPathInfos();
        List<CreatePathRequest.PathInfo> validRequests =
                new ArrayList<>(request.getPathInfos().size());
        List<HemerocallisPath> currentPaths = pathRepository.findAllByServiceName(
                pathInfos.get(0).getServiceName()//这里可能会出现索引越界异常,调用方需要注意
        );

        if(!CollectionUtils.isEmpty(currentPaths)) {
            for (CreatePathRequest.PathInfo pathInfo: pathInfos) {
                boolean isValid = true;

                for (HemerocallisPath currentPath : currentPaths) {
                    if(currentPath.getPathPattern()
                            .equals(pathInfo.getPathPattern()) &&
                            currentPath.getHttpMethod().equals(pathInfo.getHttpMethod())) {
                        isValid = false;
                        break;
                    }
                }

                if (isValid) {
                    validRequests.add(pathInfo);
                }
            }
        } else {
            validRequests = pathInfos;
        }

        List<HemerocallisPath> paths = new ArrayList<>(validRequests.size());
        validRequests.forEach(p -> paths.add(
                new HemerocallisPath(
                        p.getPathPattern(),
                        p.getHttpMethod(),
                        p.getPathName(),
                        p.getServiceName(),
                        p.getOpMode()
                )
        ));

        return pathRepository.saveAll(paths)
                .stream().map(HemerocallisPath::getId).collect(Collectors.toList());
    }

}
